package nl.rainbowsheep.reisorg.cust.site.controller;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import nl.rainbowsheep.reisorg.cust.site.service.CustomerService;
import nl.rainbowsheep.reisorg.cust.site.service.UserService;
import nl.rainbowsheep.reisorg.cust.site.viewmodel.CustomerViewmodel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * Customer controller to delegate requests
 *
 */
@Controller
@RequestMapping("/customer")
public class CustomerController {

    /**
     * use slf4j logger during debugging
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomerController.class);

    @Autowired
    CustomerService customerService;

    @Autowired
    UserService userservice;

    @RequestMapping(value = {"/index", "", "/"})
    public String CustomerIndex() {
        return "customer/index";
    }

    /**
     * Method is necessary to convert string to date.
     *
     * @param request the HttpServletRequest
     * @param binder the ServletRequestDataBinder
     */
    @InitBinder
    protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        dateFormat.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    /**
     * Method to get the view to register and bind a CustomerViewmodel object to it
     *
     * @return ModelAndView CustomerViewmodel object
     */
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public ModelAndView getRegisterForm() {
        ModelAndView modelandview = new ModelAndView();
        modelandview.addObject("customerViewmodel", new CustomerViewmodel());

        return modelandview;
    }

    /**
     * Method to post a customer by CustomerService to rest service.
     *
     * @param customerViewmodel
     * @param bindingResult checks for validation
     * @param model
     * @return viewname for customer index
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public ModelAndView createCustomer(@ModelAttribute("customerViewmodel") @Valid CustomerViewmodel customerViewmodel, BindingResult bindingResult, ModelAndView model) {
        if (bindingResult.hasErrors()) {
            return model;
        }
        customerViewmodel.getBurritoUser().setId(-1);
        try {
            CustomerViewmodel customerViewmodelSaved = customerService.insertCustomerViewmodel(customerViewmodel);
        } //hacked error voor wanneer username al bezet is.
            //gaan we ook nog op mailadressen checken?
        catch (Exception ex) {
            bindingResult.rejectValue("burritoUser.username", "error.burritoUser.username_lbl", "An account already exists with this username");
            return model;
        }
            return new ModelAndView("login");
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public ModelAndView updateCustomer(@ModelAttribute("customerviewmodel")
            @Valid CustomerViewmodel updatedCustomerviewmodel, BindingResult bindingResult, ModelAndView model, HttpSession session) {
        if (bindingResult.hasErrors()) {
            return model;
        }
        CustomerViewmodel sessionCustomerViewmodel = (CustomerViewmodel) session.getAttribute("customerviewmodelreq");
        updatedCustomerviewmodel.getCustomer().setBurritoUserId(sessionCustomerViewmodel.getCustomer().getBurritoUserId());
        updatedCustomerviewmodel.getCustomer().setRegistrationDate(sessionCustomerViewmodel.getCustomer().getRegistrationDate());
        updatedCustomerviewmodel.setBurritoUser(sessionCustomerViewmodel.getBurritoUser());
        updatedCustomerviewmodel.setTravelGroups(sessionCustomerViewmodel.getTravelGroups());
        CustomerViewmodel customersaved = customerService.updateCustomerViewmodel(updatedCustomerviewmodel);
        return model;
    }

    /**
     * Method to get the details for the current user
     *
     * @param principal get current user with principal object
     * @param session
     * @return ModelAndView of details page of current user
     */
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView getCustomerDetails(Principal principal, HttpSession session) {

        String currentUserName = principal.getName();
        CustomerViewmodel customerviewmodel = customerService.getCustomerViewmodelByUsername(currentUserName);
        session.setAttribute("customerviewmodelreq", customerviewmodel);
        ModelAndView modelandview = new ModelAndView();
        modelandview.addObject("customerviewmodel", customerviewmodel);
        return modelandview;
    }

    @RequestMapping(value = "/passwordreset", method = RequestMethod.GET)
    public ModelAndView getResetPasswordForm() {
        ModelAndView modelandview = new ModelAndView();
        modelandview.addObject("customerViewmodel", new CustomerViewmodel());
        return modelandview;
    }

    @RequestMapping(value = "/passwordreset", method = RequestMethod.POST)
    public String getResetPasswordForm(@ModelAttribute("customerViewmodel") @Valid CustomerViewmodel customerViewmodel, BindingResult bindingResult, ModelAndView model) {
        if (customerService.requestResetPassword(customerViewmodel)) {
            return "customer/resetsuccess";
        }
        return "customer/passwordreset";
    }
}
